<?php
namespace control;
// 考勤统计
class attendanceStatisticsClass extends adIndexClass
{
    private const page = 'attendanceStatistics';
    private array $list = ['board' => '数据看板', 'dep_statistics' => '部门汇总'];

    /*返回网页*/
    public function home()
    {
        $root = root;
        // 搜索文本框
        $searchTxt =
            "<form name='mainForm'><span class='time_switching' onclick=\"timeSwitching('1')\">今天</span><span class='time_switching' onclick=\"timeSwitching('2')\">昨天</span><span class='time_switching' onclick=\"timeSwitching('3')\">本周</span><span class='time_switching' onclick=\"timeSwitching('4')\">本月</span>" .
            text([
                'name' => 'date',
                'title' => "时间段",
                "class" => "text text-data width200",
                "value" => $this->date.' ~ '.$this->date,
                'laydate' => ['range' => '~', 'type' => 'date',],
            ]) .
            selectMultiple(["name" => "departmentId", 'table' => " department", 'class' => " text width200", 'sqlId' => 'id', 'sqlField' => 'name', 'title' => '部门']).
            "<input class='searchSub' type='button' onclick='cardSearch()' value='查询'></form>";

        //$record = query('user_setting',"stid = '".self::$stid."' and type = '考勤统计'");
        $setting = ["board", "dep_statistics"];
        $board = in_array('board', $setting) ? 'display:block;' : 'display:none;';
        $dep_statistics = in_array('dep_statistics', $setting) ? 'display:block;' : 'display:none;';
        $html = <<<EOT
        <style>
            .title-card-li-content{
              text-align: center;padding-top: 50px
            }
            .title-card-li-money{
              font-size: 28px;font-weight: bold
            }
            .spread-box{
                float: left;
                margin: 5px 0 -5px 0;
                width: 98.5%;
            }
            .time_switching{
                display: inline-block;
                width: 80px;
                height: 26px;
                line-height: 26px;
                background-color: #e6e6e6;
                text-align: center;
                margin-right: 15px;
                cursor: pointer;
            }
            .text-data{
                margin-right: 15px;
            }
            .quarter {
                width: 16%;
            }
        </style>
        <!--<div class="chart_setting"><img onclick="layer('salesReportForm','setting',{})" src="{$root}img/control/menu_two.svg" alt=""></div>-->
        <div class="home-warp">
            <div class="spread-box">
                <div class="data-widget search">$searchTxt</div>
            </div>
            <div class="left-box" style="width: 98.5%;overflow: hidden;">
                <div class="data-widget" style="{$board}">
                    <span class="title-card">数据看板</span>
                    <ul class="revenue" id="boardHtml">
                        <li class="quarter left vertical-line">
                            <div class="title-card-li-content">
                               <div>应到人次</div>
                               <div><span class="title-card-li-money">0</span><span>人</span></div>
                            </div>
                        </li>
                        <li class="quarter left vertical-line">
                            <div class="title-card-li-content">
                               <div>实到人次</div>
                               <div><span class="title-card-li-money">0</span><span>人</span></div>
                            </div>
                        </li>
                        <li class="quarter left vertical-line">
                             <div class="title-card-li-content">
                               <div>请假人次</div>
                               <div><span class="title-card-li-money">0</span><span>人</span></div>
                            </div>
                        </li>
                        <li class="quarter left vertical-line">
                         <div class="title-card-li-content">
                               <div>迟到人次</div>
                               <div><span class="title-card-li-money">0</span><span>人</span></div>
                            </div>
                        </li>
                        <li class="quarter left vertical-line">
                         <div class="title-card-li-content">
                               <div>旷工人次</div>
                               <div><span class="title-card-li-money">0</span><span>人</span></div>
                            </div>
                        </li>
                        <li class="quarter left vertical-line">
                         <div class="title-card-li-content">
                               <div>固定工资指出</div>
                               <div><span class="title-card-li-money">￥0</span><span>万</span></div>
                            </div>
                        </li>
                    </ul>
                </div>
                <div class="half left data-widget" style="width: 98.1%;{$dep_statistics}">
                    <p><span class="title-card">部门汇总</span></p>
                   <div class="data-box-show" id="depStatisticsHtml"></div>
                </div>
            </div>
        </div>
    </div>
     <script src='{$this->root}static/javascript/echarts.min.js'></script>
<script>
function timeSwitching(type) {
    $.post(root + "control/adIndex.html?cla=salesReportForm&fun=timeSwitching", {type:type}, function (data) {
         $("[name='date']").val(data.date);
         cardSearch();
    }, "json");
}
function search_line(form,cla,fun) {
     $("#" + fun + "Html").html("数据查询中，请稍后。。。");
     //串联表单
        var formName = form.split(",");
        var serialize = "";
        var a = "";
        for (var i = 0; i < formName.length; i++) {
            if (serialize == "") {
                a = "";
            } else {
                a = "&";
            }
            if (formName[i] != "") {
                serialize += a + $("[name=" + formName[i] + "]").serialize();
            }
        }
    $.post(root + "control/adIndex.html?cla=" + cla + "&fun=" + fun, serialize, function (data) {
         $("#" + fun + "Html").html(data.html);
    }, "json");
}


/**
* 看板搜索
*/
function cardSearch(){
    ['board', 'depStatistics'].forEach((fun)=>{
        search_line('mainForm','attendanceStatistics', fun)
    })
}

$(function() {
    ['board', 'depStatistics'].forEach((fun)=>{
        search_line('mainForm','attendanceStatistics', fun)
    })
})


</script>
EOT;
        $style = '<style>#body{background-color:#f2f2f2;padding:0 10px}.right-box-ul{
            height: 500px;
            max-height: none;
         }
         .right-box-title{
            display: flex;
         }
         .right-text{
            height: auto;
         }
         .right-box-title li{
            float: left;margin: 5px 10px;min-width: 70px;text-align: center;
         }
         .data-widget-select{
            margin-right: 10px;
         }
         .data-widget-select .fs-label{
             height: 15px;line-height: 15px;
         }
         .data-widget-select .fs-label-wrap{
             border-radius: 4px;
         }
         .aim-rank li{
            margin: 5px 0;
         }
         .aim-rank .right-box-title li:nth-child(1){min-width: 40px}
         .aim-rank .right-box-title li:nth-child(2){min-width: 50px}
         .aim-rank .right-box-title li:nth-child(3){min-width: 100px}
         .aim-rank .right-box-title li:nth-child(4){min-width: 100px}
</style>';
        return head("ad") . $style . $this->adheader(["主页"]) . $html . warn() . $this->adfooter();
    }

    /**
     * 时间选择切换
     * @return bool|string
     */
    public function timeSwitching(): bool|string
    {
        $type = $this->post('type') ?: 1;
        switch ($type) {
            case 2:
                $json['date'] = date('Y-m-d', strtotime("-1 day")) . ' ~ ' . date('Y-m-d', strtotime("-1 day"));
                break;
            case 3:
                $json['date'] = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - date("w") + 1, date("Y"))) . ' ~ ' . date("Y-m-d", mktime(23, 59, 59, date("m"), date("d") - date("w") + 7, date("Y")));
                break;
            case 4:
                $json['date'] = date("Y-m-01") . ' ~ ' . date("Y-m-t");
                break;
            default:
                $json['date'] = date('Y-m-d') . ' ~ ' . date('Y-m-d');
                break;
        }
        return json_encode($json, 320);
    }

    /**
     * 显示设置
     * @return bool|string
     */
    public function setting()
    {
        $list = $this->list;
        $li = '';
        $index = 0;
        $setting = query('user_setting', "type='考勤统计' and stid = '" . self::$stid . "'");
        $setText = (array)json_decode($setting['value'], true);
        foreach ($list as $id => $name) {
            $index++;
            $checked = '';
            if (in_array($id, $setText)) {
                $checked = 'checked';
            }
            $li .= <<<eof
 <li><div class="li-content"><span class="left">{$name}</span><div class="switch">
                  <input id="cmn-toggle-{$index}" name='setting[]' value='{$id}' $checked class="cmn-toggle cmn-toggle-round" type="checkbox">
                  <label for="cmn-toggle-{$index}"></label>
            </div></div></li>
eof;
        }
        //生成表单
        $html = <<<efo
<form name="settingForm">
<div class="setting-content">
    <ul>
       {$li}
    </ul>
   
</div>
<div style="width: 100%;text-align: center"><button class="button" onclick="subForm('settingForm',root+'control/adIndex.html?cla=salesReportForm&fun=settingEdit')">保存</button></div>
</form>
<style>
.li-content{height: 30px;line-height: 30px}
.setting-content>ul{margin: 25px}
.setting-content>ul>li{width: 100%;border-bottom: 1px solid #F2F2F2;padding: 8px 0;}
.switch{display: inline-block;vertical-align: bottom;float: right}
</style>
efo;

        //返回弹出层
        return $this->layer(array("title" => '设置图表展示', "height" => 550, "width" => 400, "html" => $html));
    }

    /**
     * 图标展示设置
     * @return bool|string
     */
    public function settingEdit(): bool|string
    {
        $setting = $this->post('setting') ?: [];
        $record = query('user_setting', "type='考勤统计' and stid = '" . self::$stid . "'");
        if (!empty($record['id'])) {
            $json['warn'] = static::update(array(
                'table' => 'user_setting',
                'field' => [
                    'value' => json_encode($setting, 320)
                ],
                'where' => "id = '$record[id]'"
            ));
        } else {
            $json['warn'] = static::insert(array(
                'table' => 'user_setting',
                'field' => [
                    'stid' => self::$stid,
                    'type' => '考勤统计',
                    'value' => json_encode($setting, 320)
                ],
            ));
        }
        if (in_array($json['warn'], ['新增成功', '更新成功'])) {
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }


    /**
     * 数据看板
     */
    public function board(): bool|string
    {
        $date = $this->post('date');
        $departmentId = $this->post('departmentId');
        $json['html'] = '';
        //应到人次
        if (!empty($date)) {
            $timeArr = explode(' ~ ', $date);
        } else {
            $timeArr[0] = date('Y-m') . '-01';
            $timeArr[1] = $this->date;
        }
        $and     = '';
        if ($departmentId) {
            $departments = homepageClass::getDepartmentSub(["where" => " pid = '$departmentId' "]);
            $departments = array_merge([$departmentId], explode(',', trim($departments)));
            $and         .= "  and jobId in (select id from job where departmentId in ('" . implode("','", $departments) . "')) ";
        }
        $shouldArrive = find([
                'table'  => "staff",
                'field'  => "IFNULL(count(stid),0) as num",
                'single' => " 1 and quitDay > '$timeArr[1]' ".$and,
            ])['num'] ?? 0;
        $json['html'] .= <<<efo
                        <li class="quarter left vertical-line">
                            <div class="title-card-li-content">
                               <div>应到人数</div>
                                <div><span class="title-card-li-money">{$shouldArrive}</span><span>人</span></div>
                            </div>
                        </li>
         
efo;
        //实到人数
        $where = "";
        if ($date) {
            $where .= $this->timeComparison($date, 'date', 'date');
        }
        $actualArrive = find([
                'table'  => "work_sign_single",
                'field'  => "IFNULL(count(id),0) as num",
                'single' => " 1 ".$where.$and,
            ])['num'] ?? 0;
        $json['html'] .= <<<efo
                        <li class="quarter left vertical-line">
                            <div class="title-card-li-content">
                                <div>实到人数</div>
                                <div><span class="title-card-li-money">{$actualArrive}</span><span>人</span></div>
                            </div>
                        </li>
         
efo;
        //请假人数
        $where = "";
        if ($date) {
            $where .= $this->timeComparison($date, 'date', 'startTime');
        }
        $holidayNum = find([
                'table'  => "work_holiday",
                'field'  => "IFNULL(count(id),0) as num",
                'single' => " 1 and state = '已通过' and stid in (select stid from staff where 1 {$and}) ".$where,
            ])['num'] ?? 0;
        $json['html'] .= <<<efo
                        <li class="quarter left vertical-line">
                            <div class="title-card-li-content">
                                <div>请假人数</div>
                                <div><span class="title-card-li-money">$holidayNum</span><span>人</span></div>
                            </div>
                        </li>
         
efo;
        //迟到人数
        $where = "";
        if ($date) {
            $where .= $this->timeComparison($date, 'date', 'date');
        }
        $lateNum = find([
                'table'  => "work_sign_single",
                'field'  => "IFNULL(count(id),0) as num",
                'single' => " 1 and late = 1 ".$where.$and,
            ])['num'] ?? 0;
        $json['html'] .= <<<efo
                        <li class="quarter left vertical-line">
                            <div class="title-card-li-content">
                                <div>迟到人数</div>
                                <div><span class="title-card-li-money">$lateNum</span><span>人</span></div>
                            </div>
                        </li>
         
efo;
        //旷工人数
        $where = "";
        if ($date) {
            $where .= $this->timeComparison($date, 'date', 'date');
        }
        $leaveNum = find([
                'table'  => "work_sign_single",
                'field'  => "IFNULL(count(id),0) as num",
                'single' => " 1 and is_leave = 1 ".$where.$and,
            ])['num'] ?? 0;
        $json['html'] .= <<<efo
                        <li class="quarter left vertical-line">
                            <div class="title-card-li-content">
                                <div>旷工人数</div>
                                <div><span class="title-card-li-money">$leaveNum</span><span>人</span></div>
                            </div>
                        </li>
         
efo;
        //固定工资支出
        $total = 0;
        $staff = find([
                'table'  => "staff",
                'field'  => "stid",
                'where' => " 1 and quitDay > '$timeArr[1]' ".$and,
            ]);
        $workSignCheckClass = new workSignCheckClass();
        foreach ((array)$staff['array'] as $val){
            $lastMonthTime = $workSignCheckClass->lastMonthTime(date("Y-m",strtotime($timeArr[0])));//最后一天时间 获取有效薪酬规则
            //根据员工选择器的值和当前员工的部门，职位，员工ID求交集
            $idColloection = $workSignCheckClass->staffCombination(true,$val['stid']);
            //薪酬规则,取生效日期小于当月最后一天的时间，排序最新的那条规则
            $salaryRule = query('salary_rule', " (concat(',',replace(selector,';',','),',') regexp concat(',',replace('{$idColloection}',',',',|,'),','))>0 and state = '启用' and UNIX_TIMESTAMP(startTime) <=UNIX_TIMESTAMP('{$lastMonthTime}') order by startTime desc");
            $total += (float)$salaryRule['baseMoney'] + (float)$salaryRule['jobMoney'];
        }
        $text = $total > 10000 ? '万' : '';
        $money = round($total > 10000 ? ($total / 10000) : $total, 2);
        $json['html'] .= <<<efo
                        <li class="quarter left vertical-line">
                            <div class="title-card-li-content">
                                <div>固定工资支出</div>
                                <div><span class="title-card-li-money">{$money}</span><span>{$text}</span></div>
                            </div>
                        </li>
         
efo;
        return json_encode($json, 320);
    }
    /*部门汇总-查询结果*/
    public function depStatistics()
    {
        //日期
        $date = $this->post('date');
        if (!empty($date)) {
            $timeArr = explode(' ~ ', $date);
        } else {
            $timeArr[0] = date('Y-m') . '-01';
            $timeArr[1] = $this->date;
        }
        //部门
        $department = $this->post('departmentId');
        //未选部门时列示所有一级部门
        if (empty($department)) {
            $page = $this->page(array("table" => "department", 'field' => "id,name", "where" => "  pid = '0' ", "order" => " list asc "));
        } else {
            $page = $this->page(array("table" => "department", 'field' => "id,name", "where" => "  pid = '$department' ", "order" => " list asc "));
            //没有下级部门的列示本部门
            if (static::isNull($page['array'])) {
                $page = $this->page(array("table" => "department", 'field' => "id,name", "where" => "  id = '$department' ", "order" => " list asc "));
            }
        }
        //获取表头
        $tr[] = array("部门", "应到人数", "实到人数", '请假人数', '迟到人数', '旷工人数', '固定工资支出');
        //获取记录
        foreach ($page['array'] as $array) {
            $departments = homepageClass::getDepartmentSub(["where" => " pid = '$array[id]' "]);
            $departments = array_merge([$array['id']], explode(',', trim($departments)));
            $and = "  and jobId in (select id from job where departmentId in ('" . implode("','", $departments) . "')) ";
            $shouldArrive = find([
                    'table'  => "staff",
                    'field'  => "IFNULL(count(stid),0) as num",
                    'single' => " 1 and quitDay > '$timeArr[1]' ".$and,
                ])['num'] ?? 0;
            //实到人数
            $where = "";
            if ($date) {
                $where .= $this->timeComparison($date, 'date', 'date');
            }
            $actualArrive = find([
                    'table'  => "work_sign_single",
                    'field'  => "IFNULL(count(id),0) as num",
                    'single' => " 1 ".$where.$and,
                ])['num'] ?? 0;
            //请假人数
            $where = "";
            if ($date) {
                $where .= $this->timeComparison($date, 'date', 'startTime');
            }
            $holidayNum = find([
                    'table'  => "work_holiday",
                    'field'  => "IFNULL(count(id),0) as num",
                    'single' => " 1 and state = '已通过' and stid in (select stid from staff where 1 {$and}) ".$where,
                ])['num'] ?? 0;
            //迟到人数
            $where = "";
            if ($date) {
                $where .= $this->timeComparison($date, 'date', 'date');
            }
            $lateNum = find([
                    'table'  => "work_sign_single",
                    'field'  => "IFNULL(count(id),0) as num",
                    'single' => " 1 and late = 1 ".$where.$and,
                ])['num'] ?? 0;
            //旷工人数
            $where = "";
            if ($date) {
                $where .= $this->timeComparison($date, 'date', 'date');
            }
            $leaveNum = find([
                    'table'  => "work_sign_single",
                    'field'  => "IFNULL(count(id),0) as num",
                    'single' => " 1 and is_leave = 1 ".$where.$and,
                ])['num'] ?? 0;
            //固定工资支出
            $total = 0;
            $staff = find([
                'table'  => "staff",
                'field'  => "stid",
                'where' => " 1 and quitDay > '$timeArr[1]' ".$and,
            ]);
            $workSignCheckClass = new workSignCheckClass();
            foreach ((array)$staff['array'] as $val){
                $lastMonthTime = $workSignCheckClass->lastMonthTime(date("Y-m",strtotime($timeArr[0])));//最后一天时间 获取有效薪酬规则
                //根据员工选择器的值和当前员工的部门，职位，员工ID求交集
                $idColloection = $workSignCheckClass->staffCombination(true,$val['stid']);
                //薪酬规则,取生效日期小于当月最后一天的时间，排序最新的那条规则
                $salaryRule = query('salary_rule', " (concat(',',replace(selector,';',','),',') regexp concat(',',replace('{$idColloection}',',',',|,'),','))>0 and state = '启用' and UNIX_TIMESTAMP(startTime) <=UNIX_TIMESTAMP('{$lastMonthTime}') order by startTime desc");
                $total += (float)$salaryRule['baseMoney'] + (float)$salaryRule['jobMoney'];
            }
            $tr[] = array($array['name'], $shouldArrive, $actualArrive, $holidayNum, $lateNum,
                $leaveNum, $total);
        }
        //控件
        $button = "";
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . space . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

}
